package com.foolishbird.sdk.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.bean.GameNoticeModel;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.utils.ResUtils;

import java.util.ArrayList;
import java.util.List;

public class FoolishBirdNoticeFragment extends BaseDialogFragment implements View.OnClickListener {

    private List<GameNoticeModel> gameNoticeModels= new ArrayList<>();

    public static final FoolishBirdNoticeFragment newInstance(Bundle bundle) {
        FoolishBirdNoticeFragment fragment = new FoolishBirdNoticeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

//    private ListView titleListView;
    private ImageView closeBtn;
    private ViewPager viewPager;
    private LinearLayout viewGroup;
    private ImageView[] imageViews;
    private CheckBox noNoticeCheck;

//    private Button contactBtn;
//    private TextView titleText;
//    private GameNoticeListAdapter mListAdapter;
//    private WebView contentWebview;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//
//        getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        setCancelable(false);
        Bundle bundle = getArguments();
        if(bundle.containsKey("notice")){
            gameNoticeModels = (ArrayList<GameNoticeModel>)bundle.getSerializable("notice");
            Log.e("notice",""+gameNoticeModels.size());
        }
//        int noticeType = 0;
//        if(bundle.containsKey("popupConfig")){
//            PopupConfig popupConfig = bundle.getParcelable("popupConfig");
//            noticeType = popupConfig.getNoticeUIType();
//        }
//        View contentView = doInflateContentView(inflater, container,
//                noticeType==1?
//                getLayoutIdentifier("hnssn_fragment_game_notice"):
//                        getLayoutIdentifier("hnssn_fragment_game_notice_chuanqi"));
        View contentView = doInflateContentView(inflater,container,getLayoutIdentifier("fb_fragment_notice"));
        closeBtn = contentView.findViewById(getViewIdentifier("fb_fragment_login_close"));
        closeBtn.setOnClickListener(this);
        viewPager = contentView.findViewById(getViewIdentifier("fb_fragment_notice_viewPager"));
        noNoticeCheck = contentView.findViewById(getViewIdentifier("fb_fragment_notice_checkbox"));
        viewPager.setAdapter(new GuidePageAdapter());
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 遍历数组让当前选中图片下的小圆点设置颜色
                for (int i = 0; i < imageViews.length; i++) {


                    if (position != i) {
                        imageViews[i]
                                .setBackgroundResource(getDrawableIdentifier("fb_index_uncheck"));
                    }else{
                        imageViews[i]
                                .setBackgroundResource(getDrawableIdentifier("fb_index_check"));
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewGroup = contentView.findViewById(getViewIdentifier("fb_fragment_notice_viewGroup"));

        setData();
        return contentView;
    }

    private void setData(){
        imageViews = new ImageView[gameNoticeModels.size()];
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置每个小圆点距离左边的间距
        margin.setMargins(10,0, 0, 0);
        for (int i = 0; i < gameNoticeModels.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            // 设置每个小圆点的宽高
            imageView.setLayoutParams(new LinearLayout.LayoutParams(ResUtils.dip2px(getContext(),8), ResUtils.dip2px(getContext(),8)));
            imageViews[i] = imageView;
            if (i == 0) {
                // 默认选中第一张图片
                imageViews[i]
                        .setBackgroundResource(getDrawableIdentifier("fb_index_check"));
            }else{
                // 其他图片都设置未选中状态
                imageViews[i]
                        .setBackgroundResource(getDrawableIdentifier("fb_index_uncheck"));
            }
            viewGroup.addView(imageViews[i], margin);
        }

    }


    // 指引页面数据适配器
    class GuidePageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return gameNoticeModels.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }



        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
//            return super.instantiateItem(container, position);
            GameNoticeModel model = gameNoticeModels.get(position);

            final int layoutResId = ResUtils.getLayoutIdentifier(getContext(), "fb_fragment_notice_item");
            final int titleResId = ResUtils.getViewIdentifier(getContext(), "notice_item_title");
            final int contentResId = ResUtils.getViewIdentifier(getContext(), "gamenotice_content");
            View view = LayoutInflater.from(getContext()).inflate(layoutResId,null);
            TextView titleView = view.findViewById(titleResId);
            WebView contentView = view.findViewById(contentResId);
            contentView.setBackgroundColor(0);
            contentView.getBackground().setAlpha(0);
            contentView.setWebViewClient(new WebViewClient(){
                                                @Override
                                                public void onPageFinished(WebView view, String url) {
                                                    super.onPageFinished(view, url);
                                                    view.scrollTo(0,0);
                                                }
                                            }
            );
            titleView.setText(model.getTitle());

            contentView.loadDataWithBaseURL(null, model.getContent(), "text/html", "utf-8", null);
            container.addView(view);
            return view;

        }
    }




    @Override
    public void onClick(View v) {

        if(v.equals(closeBtn)){
            if(noNoticeCheck.isChecked()){
                HttpEngineApi.getInstance().getEngineConduits().saveNoMoreNotice();
            }
            OnFinishActivityListener listener = getOnFinishActivityListener();
            if (listener != null) {
                listener.doFinishActivity(this);
            }
        }
//        else if(v.equals(titleText)){
//            GameNoticeModel modle = mListAdapter.getSelectItem();
//
//
//            Intent intent = new Intent(getActivity(), FloatExtensionBarActivity.class);
//            WindowMessage message = new WindowMessage();
//            message.setJumpType(modle.getJumpToTab().equals("service")?"customer":modle.getJumpToTab());
//            if(!TextUtils.isEmpty(modle.getExtraField())){
//                message.setAppendString("&"+modle.getExtraField()+"="+modle.getArticleId());
//            }
//            intent.setPackage(getActivity().getPackageName());
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.putExtra(Constant.LocalIntentExtra.INTENT_FLOAT_WINDOW_DATA,message);
//            getActivity().startActivity(intent);
//        }
//        else if (v.equals(contactBtn)){
//            GameNoticeModel modle = mListAdapter.getSelectItem();
//
//
//            Intent intent = new Intent(getActivity(), FloatExtensionBarActivity.class);
//            WindowMessage message = new WindowMessage();
//            message.setJumpType(modle.getJumpToTab().equals("service")?"customer":modle.getJumpToTab());
//            intent.setPackage(getActivity().getPackageName());
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.putExtra(Constant.LocalIntentExtra.INTENT_FLOAT_WINDOW_DATA,message);
//            getActivity().startActivity(intent);
//
//        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            FragmentActivity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }
}
